<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Friends;
use App\Models\LoginUser;
use App\Models\Config;
use App\Models\SoftGoods;

class ApiController extends Controller
{
    //通讯录上传
    public function friends_up(Request $request){
        $username = $request->get('username');
        $friends = $request->getContent();
        Friends::where('Username',$username)->delete();
        $friends = json_decode($friends,true);
        foreach($friends['data'] as $v){
            $answers[] = [
                        'wxid' => $v['wxid'],
                        'nickname' => base64_encode($v['nickname']),
                        'Username' => $username
                    ];
        }
        $res = Friends::insert($answers);//返回1
        return $res;
    }
    //读取配置接口
    public function read_config(Request $request){
        $username = $request->get('username');
        $users = LoginUser::where('username',$username)->get(['UnionId','start_time','end_time','fd_status','room_desc','at_time','goods_rest','img_rest'])->first();
        $fadans = Config::where('status',1)->get();
        $caijis = Config::where('status',2)->get();
        $return["code"] =0;
        $return["users"] = $users;
        $return["fadans"] = $fadans;
        $return["caijis"] = $caijis;
        return $return;
    }
    //转链接口
    public function promotion(Request $request){
        $return["unionid"] = $request->get('unionid');
        $return["positionid"] = $request->get('positionid');
        $filedata = $request->getContent();
        // return $filedata;
        $union_url_arry = extract_jdunionurl($filedata);//遍历u.jd.com链接数组
        $num = count($union_url_arry);
        // return $num;
        $short_url_arry = array();//原始文案中的推广链接数组
        $promotion_url_arry = array();//转链后的推广链接数组
        for($i = 0; $i < $num; $i++){
              array_push($short_url_arry , $union_url_arry[$i]);

              $resp = promotion_byunionid_get($return["unionid"],$return["positionid"],$union_url_arry[$i]);
              // "{"code":2001906,"message":"优惠券已过期","requestId":"o_0b12805e_l6tfhzm3_290674698"}"
              // "{"code":200,"data":{"shortURL":"https://u.jd.com/RCVaGNY"},"message":"success","requestId":"o_0b648122_l6tfivi0_251701621"}"
              $return["resp"] = $resp;
              $return = json_decode($resp , true);
              // return $result;
              // return $result['code'];//200
              // {"code":200,"data":{"shortURL":"https:\/\/u.jd.com\/RwVQZv0"},"message":"success","requestId":"o_0b12b382_l6thb19k_290956190"}
              if($return["code"] == 200){
                  array_push($promotion_url_arry,$return["data"]["shortURL"]);
              }else{
                  $return["code"] = 1;
                  array_push($promotion_url_arry,"error:".$return["message"]);
              }
              if($i+1 < $num){
                  sleep(0.5);
              }
          }
          $filedata = str_replace($short_url_arry,$promotion_url_arry,$filedata);
            // return $filedata;
          $return["short_url_arry"] = $short_url_arry;
          $return["promotion_url_arry"] = $promotion_url_arry;

        if($return["code"] == 1){
        	return json_encode($return,JSON_UNESCAPED_UNICODE);
        }else{
        	return $filedata;
        }
    }
    public function caiji_up(Request $request){
        $username = $request->get('username');
        $str = $request->getContent();
        // return $filedata;
        $str = file_get_contents('php://input');//获取post数据
        preg_match_all('%https?:\/\/.*?\s%is',$str,$arr);//能匹配到优惠券地址
        $num = count($arr[0]);
        $longurl_arr=array();
        $shorturl_arr=array();
        $change = '';
        // 1,优惠券链接转短
        for($i=0; $i < $num; $i++){
        	if(strstr($arr[0][$i], 'coupon')){
        		 $longurl=$arr[0][$i];
        		 $longurl = str_replace("\n","",$longurl);
        		 $longurl = str_replace("\r","",$longurl);
        		 array_push($longurl_arr,$longurl);
        		 $shorturl = mtw_url($longurl);
        		 array_push($shorturl_arr,$shorturl);
        		 $change = 1;
        		 // sleep(0.5);
        		 // break;
        	}

        }
        //2、遍历取u.jd.com
        preg_match_all("/https:[\/]{2}[a-z]+[.]{1}[a-z\d\-]+[.]{1}[a-z\d]*[\/]*[A-Za-z\d]*[\/]*[A-Za-z\d]*/",$str,$arr);
        //匹配不到优惠券地址，如果匹配不到u.jd.com就用这个匹配,提取主图
        $num = count($arr[0]);
        // $return = array();
        for($i=0; $i < $num; $i++){
        	if(strstr($arr[0][$i], 'u.jd.com')){

        			 $url = $arr[0][$i];
        			 $url = str_replace("\n","",$url);

        			 $resp = UnionOpenGoodsQueryRequest($url);
        			 // return $resp;
        			 $arry = json_decode($resp,true);

        			 if($arry['totalCount']==1){
                        $return["code"] = 0;
        				$return['imgurl'] = $arry['data'][0]['imageInfo']['imageList'][0]['url'];
        				$return['msg']  = "提取成功";
        				break;
        			 }else{
        				 $return['code']  = 1;
        				 $return['msg']  = "主图提取失败，请检查推广链接";
        			 }


        	}
        }
        if($return["code"] == 0){//判断主图是否提取成功
        	$return['url']  = $url;
        	$return['longurl']  = $longurl_arr;
        	$return['shorturl']  = $shorturl_arr;
        	if($change == 1){
        		$return['docment']  = str_replace($longurl_arr,$shorturl_arr,$str);
        	}else{
        		$return['docment']  = $str;
        	}

        	//上传到数据库
        	$data = [
        		'status' => '0',
        	    'goodsImage' => $return['imgurl'],
        		'docment' => base64_encode($return['docment']),
        		'in_time' => date('Y-m-d H:i:s',time()),
                'username' => $username
                ];

        	$id = SoftGoods::where('username',$username)->create($data);
            // return $id->ID;//返回自增ID
            $id = $id->ID;//返回自增ID
        	if ($id){
                SoftGoods::where('ID',$id)->update(['index' => $id]);
        		$return['code']  = 0;
        		$return['id']  = $id;
        		$return['msg']  = "推送成功";
        		}
        	else{
        		$return['code']  = 1;
        		$return['msg']  = 'insert failed: update ID error';
        		}
        }
        return response()->json($return);
    }
    public function login(Request $request){
        $L_username = $request->get('L_username');
        $L_pass = $request->get('L_pass');
        // return $L_pass;
        // return gettype($L_pass);
        $user = LoginUser::where('username',$L_username)->get()->first();
        // return gettype($user);
        if(is_object($user)){
            // return '返回的是对象';
            // return $user->password;
            // return gettype($user->password);
            if($user->password == $L_pass){
                $return['code'] = 0;
                $return['nicheng'] = $user->nickname;
                $return['username'] = $L_username;
                $return['msg'] = "账号密码正确";
            }else{
                $return['code'] = 1;
                $return['msg'] = "账号密码错误";
            }
        }else{
            // return '返回的bu是对象';
            $return['code'] = 1;
            $return['msg'] = "不存在该账号：".$L_username;
        }
        return response()->json($return);
        // return $user;
        // {
        //     "id": 1,
        //     "username": "mosheng",
        //     "password": "901025",
        //     "nickname": "莫生",
        //     "UnionId": 1100,
        //     "in_time": null,
        //     "out_time": null,
        //     "staty_time": null,
        //     "start_time": "08:00:00",
        //     "end_time": "22:00:00",
        //     "goods_rest": 6,
        //     "img_rest": 7,
        //     "fd_status": 1,
        //     "room_desc": "5qyi6L+O5p2l5Yiw8J+RjyBb576k5ZCNXSDvvZ5+Cuivt+aCqOiKsTHliIbpkp/kuobop6PkuIDkuIsK44CQ576k6KeE44CR77yaCiAx77yJ576k5Li75q+P5aSp5Li65a625Lq65Lus5Y+R6YCBSkTlpb3nianllYblk4HvvJsKIDLvvInkurLlj4vku6zlpoLmnpzmnInmjIflrprllYblk4Hnsbvlnovlj6/ku6VAIOe+pOS4u++8jOe+pOS4u+S8muaDs+WKnuazleS4uuWkp+WutuaJvuS8mOaDoOWVhuWTge+8mwogM++8ieWmguaenOaCqOinieW+l+S/oeaBr+aJk+aJsOato+W4uOW3peS9nO+8jOWPr+S7peeCueWHu+e+pOWPs+S4iuinkuiuvue9ruS4uuOAkOa2iOaBr+WFjeaJk+aJsOOAke+8jOS9huaYr+W8uueDiOW7uuiuruiuvue9ruS4uuOAkOe9rumhtuiBiuWkqeOAke+8jOiuqeS8mOaDoOS/oeaBr+abtOmGkuebru+8mwogNO+8ieWQjOaXtuS5n+aBs+ivt+WQhOS9jeS6suWPi+S4jeimgeS5seWPkeW5v+WRiuWSjOaXoOeUqOS/oeaBr++8jOe7tOaKpOWlveWSseS7rOiHquW3seeahOe+pO+8jOWBmuebuOS6suebuOeIseeahOS4gOWutuS6uuOAgg==",
        //     "at_time": 1
        // }
    }
    public function goods_list_one(Request $request){
        $username = $request->get('datebase');
        // return $username;
        $goods = SoftGoods::where('username',$username)->orderBy('index', 'ASC')->get()->first();
        // return $goods;
        return response()->json($goods);
    }
    public function goods_up(Request $request){
        $username = $request->get('username');
        $ID = $request->get('ID');
        // return $ID;
        $res = SoftGoods::where('username',$username)->where('ID', $ID)->update(['status'=>1]);
        return $res;//返回受影响行数
    }
}
